<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Attachment;
use App\Transformers\AttachmentTransformer;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;

class AttachmentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $with = [
            'commentDetails', 'commentDetails.comment',
        ];
        $userKey = $request->user_key;//筛选特定用户的
        $commentKey = $request->comment_key;
        $list = Attachment::with($with)
            ->when($userKey, function ($query) use ($userKey) {
                $query->whereHas('user', function ($query) use ($userKey) {
                    $query->where("key", $userKey);
                });
            })
            ->when($commentKey, function ($query) use ($commentKey) {
                $query->whereHas('commentDetails', function ($query) use ($commentKey) {
                    $query->whereHas("comment", function ($query) use ($commentKey) {
                        $query->where("key", $commentKey);
                    });
                });
            })
            ->paginate($request->get('per_page', 10));

//        dd($list);

        $apiData = fractal()
            ->collection($list)
            ->transformWith(new AttachmentTransformer())
            ->parseIncludes($with)
            ->paginateWith(new IlluminatePaginatorAdapter($list))
            ->toArray();

        $out = [
            'list' => $apiData['data'],
            'pagination' => $apiData['meta']['pagination'],
        ];

        return normalize(0, 'OK', $out);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
